package cn.qh.com.service.impl;

import cn.qh.com.exception.NotFoundException;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import cn.qh.com.mapper.CategoryMapper;
import cn.qh.com.entity.Category;
import cn.qh.com.service.CategoryService;
import org.springframework.stereotype.Service;

import java.util.*;

/**
 * 商品三级分类(Category)表服务实现类
 *
 * @author makejava
 * @since 2021-11-27 09:57:09
 */
@Service("categoryService")
public class CategoryServiceImpl extends ServiceImpl<CategoryMapper, Category> implements CategoryService {


    //树状图形式展示数据
    public List<Category> selectTree() {
        List<Category> list = this.list();
        List<Category> categoryList = new ArrayList<>();
        for (Category category : list) {
            if (category.getParentcid() == 0) {
                categoryList.add(category);
            }
        }
        Collections.sort(categoryList);
        //遍历一级的查找子分类
        for (Category category : categoryList) {
            ChildCategory(category, list);
        }
        return categoryList;
    }

    @Override
    public Boolean insertCategory(Category category) {
        int catLevel = 0;
        if (category.getParentcid() == 0) {
            catLevel = 1;
        } else {
            Long parentcid = category.getParentcid();
            Category byId = this.getById(parentcid);
            if (byId == null) {
                throw new NotFoundException(20001);
            }
            catLevel = byId.getCatlevel() + 1;
        }
        category.setCatlevel(catLevel);
        return this.save(category);
    }

    @Override
    public Boolean updateCategory(long catId, int catlevel, long parentcid) {
        Category category = new Category();
        category.setCatlevel(catlevel);
        category.setCatId(catId);
        category.setParentcid(parentcid);
        return this.updateById(category);
    }

    @Override
    public boolean deleteCategory(Long[] arrays) {
        return this.removeByIds(Arrays.asList(arrays));
    }

    public void ChildCategory(Category category, List<Category> categoryList) {
        for (Category temp : categoryList) {
            if (category.getCatId() == temp.getParentcid()) {
                category.getCategoryList().add(temp);
                ChildCategory(temp, categoryList);
            }
        }
        Collections.sort(category.getCategoryList());
    }
}

